 //
//  SYS_LoginVC.m
//  System_App
//
//  Created by czy001 on 2017/11/27.
//  Copyright © 2017年 czy001. All rights reserved.
//

#import "SYS_LoginVC.h"
#import "SYS_LoginTextView.h"
#import "SYS_LoginModel.h"
#import "SYS_RemeberPwdVC.h"

@interface SYS_LoginVC ()<UITextFieldDelegate>
@property (nonatomic,strong) SYS_LoginTextView *phoneTextView;
@property (nonatomic,strong) SYS_LoginTextView *pwdTextView;
@property (nonatomic,strong) UIButton *remeberButton;
@property (nonatomic,strong) UIButton *loginButton;
@end

@implementation SYS_LoginVC

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationItem setHidesBackButton:YES];
    self.navigationController.navigationBarHidden=YES;
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    self.navigationController.navigationBarHidden=NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title=@"登录";
    self.view.backgroundColor=DGHColor(255, 255, 255);
    
    [self initWithUI];
}

#pragma mark   -------  UI  ---------
-(void) initWithUI
{
    UIImageView *bgImageView=[[UIImageView alloc]initWithFrame:CGRectMake(0,0, SCREENWIDTH, SCREENHEIGHT)];
    bgImageView.image=[UIImage imageNamed:@"SYS_Login_bg"];
    bgImageView.userInteractionEnabled=YES;
    [self.view addSubview:bgImageView];
    
    UIImageView *logoImageView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"SYS_Login_dlylogo"]];
    
    NSString *phoneNumStr=[NSKeyedUnarchiver unarchiveObjectWithFile:PhoneFilePath];
    NSString *pwdStr=[NSKeyedUnarchiver unarchiveObjectWithFile:PhonePwdFilePath];
    
    _phoneTextView=[SYS_LoginTextView new];
    _phoneTextView.iconImageView.image=[UIImage imageNamed:@"SYS_Login_zhtb"];
    _phoneTextView.inputTextFiled.placeholder=@"请输入账号";
    _phoneTextView.inputTextFiled.keyboardType=UIKeyboardTypeNumbersAndPunctuation;
    _phoneTextView.inputTextFiled.delegate=self;
    _phoneTextView.inputTextFiled.tag=8888;
    _phoneTextView.inputTextFiled.text=phoneNumStr;
    
    _pwdTextView=[SYS_LoginTextView new];
    _pwdTextView.iconImageView.image=[UIImage imageNamed:@"SYS_Login_mima"];
    _pwdTextView.inputTextFiled.placeholder=@"请输入6~20位字符密码";
    _pwdTextView.inputTextFiled.keyboardType=UIKeyboardTypeNumbersAndPunctuation;
    _pwdTextView.inputTextFiled.secureTextEntry=YES;
    _pwdTextView.inputTextFiled.delegate=self;
    _pwdTextView.inputTextFiled.tag=9999;
    _pwdTextView.inputTextFiled.text=pwdStr;
    
    _remeberButton=[UIButton new];
    [_remeberButton setTitle:@"忘记密码?" forState:0];
    _remeberButton.titleLabel.font=[UIFont systemFontOfSize:13];
    [_remeberButton setTitleColor:DGHColor(168, 168, 168) forState:0];
    [_remeberButton addTarget:self action:@selector(remeberButtonClick) forControlEvents:UIControlEventTouchUpInside];
    
    //添加登录按钮
    _loginButton=[[UIButton alloc]init];
    [_loginButton setBackgroundColor:DGHColor(29, 173, 252)];
    [_loginButton setTitle:@"立即登录" forState:UIControlStateNormal];
    _loginButton.titleLabel.textAlignment=NSTextAlignmentCenter;
    _loginButton.titleLabel.font=[UIFont fontWithName:@"PingFangSC-Regular" size:18];
    _loginButton.titleLabel.font=[UIFont systemFontOfSize:16];
    [_loginButton setTitleColor:DGHColor(255, 255, 255) forState:UIControlStateNormal];
    _loginButton.layer.masksToBounds=YES;
    _loginButton.layer.cornerRadius=22.5;
    [_loginButton addTarget:self action:@selector(loginButtonClick) forControlEvents:UIControlEventTouchUpInside];
    
    [bgImageView sd_addSubviews:@[logoImageView,_phoneTextView,_pwdTextView,_remeberButton,_loginButton]];
    
    logoImageView.sd_layout
    .leftSpaceToView(bgImageView, (SCREENWIDTH-60)/2)
    .topSpaceToView(bgImageView, SCREENHEIGHT/2-190)
    .widthIs(60)
    .heightIs(120);
    
    _phoneTextView.sd_layout
    .leftSpaceToView(bgImageView, 0)
    .topSpaceToView(logoImageView, 0)
    .widthIs(SCREENWIDTH)
    .heightIs(60);
    
    _pwdTextView.sd_layout
    .leftSpaceToView(bgImageView, 0)
    .topSpaceToView(_phoneTextView, 0)
    .widthIs(SCREENWIDTH)
    .heightIs(60);
    
    _remeberButton.sd_layout
    .rightSpaceToView(bgImageView, 40)
    .topSpaceToView(_pwdTextView, 0)
    .widthIs(70)
    .heightIs(15);
    
    _loginButton.sd_layout
    .leftSpaceToView(bgImageView, 40)
    .topSpaceToView(_remeberButton, 40)
    .widthIs(SCREENWIDTH-80)
    .heightIs(45);
    
}

#pragma mark   --------loginButtonClick    立即登录--------
-(void) loginButtonClick
{
    NSLog(@"%@----%@",_phoneTextView.inputTextFiled.text,_pwdTextView.inputTextFiled.text);
    [self.view endEditing:YES];
    if (_phoneTextView.inputTextFiled.text.length==0) {
        [MBProgressHUD showSuccess:@"账号不能为空" toView:self.view];
        return;
    }
//    if (![SYS_HelpModel isValidateMobile:_phoneTextView.inputTextFiled.text]) {
//        [MBProgressHUD showSuccess:@"请输入正确的手机号" toView:self.view];
//        return;
//    }
    if (_pwdTextView.inputTextFiled.text.length==0) {
        [MBProgressHUD showSuccess:@"密码不能为空" toView:self.view];
        return;
    }
    UICKeyChainStore *keychainStore = [UICKeyChainStore keyChainStore];
    NSString *_passWordStr = [keychainStore stringForKey:@"pid"];
    NSDictionary *params=@{@"name":_phoneTextView.inputTextFiled.text,@"password":_pwdTextView.inputTextFiled.text,@"consoleType":@"mob",@"consoleSubType":@"iosAdm",@"pid":_passWordStr};
    [self showHudInView:self.view hint:@"正在加载..."];
    [SYS_WPJ_RequestHttpTool getSysLogin:params success:^(id returnValue) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if ([returnValue[@"flag"] isEqualToString:@"true"]) {
            NSDictionary *dataDic=returnValue[@"data"];
            SYS_LoginModel *loginModel=[SYS_LoginModel mj_objectWithKeyValues:dataDic];
            
            /********************登录信息↓↓↓↓↓↓↓↓↓***********************/
            NSDictionary *sessionDic=dataDic[@"sessionInfo"];
            NSDictionary *useDic=dataDic[@"user"];
            NSDictionary *adminDic=dataDic[@"admin"];
            
            [self loginWithUsername:[adminDic objectForKey:@"imKey"] password:[adminDic objectForKey:@"imPasswd"]];
            
            SYS_SessionInfo *sessionModel=[SYS_SessionInfo mj_objectWithKeyValues:sessionDic];
            SYS_User *userModel=[SYS_User mj_objectWithKeyValues:useDic];
            SYS_Admin *adminModel=[SYS_Admin mj_objectWithKeyValues:adminDic];
            
            loginModel.sessionInfo=sessionModel;
            loginModel.user=userModel;
            loginModel.admin=adminModel;

            [SYS_LoginModel instance].sessionInfo=sessionModel;
            [SYS_LoginModel instance].user=userModel;
            [SYS_LoginModel instance].admin=adminModel;
            
            SYS_LoginModel *loginInfo = [SYS_LoginModel mj_objectWithKeyValues:dataDic];
            NSDictionary *diccc = [loginInfo dictionaryValueBy:loginInfo];
            //存储当前登录信息
            NSFileManager * loginfileManager = [[NSFileManager alloc]init];
            [loginfileManager removeItemAtPath:LoginFilePath error:nil];
            [NSKeyedArchiver archiveRootObject:diccc toFile:LoginFilePath];
            /********************登录信息↑↑↑↑↑↑↑↑↑↑********************/

            //存储当前登录的账号
            NSFileManager * fileManager = [[NSFileManager alloc]init];
            [fileManager removeItemAtPath:PhoneFilePath error:nil];
            [NSKeyedArchiver archiveRootObject:_phoneTextView.inputTextFiled.text toFile:PhoneFilePath];
            
            //存储当前登录的密码
            NSFileManager * fileManager1 = [[NSFileManager alloc]init];
            [fileManager1 removeItemAtPath:PhonePwdFilePath error:nil];
            [NSKeyedArchiver archiveRootObject:_pwdTextView.inputTextFiled.text toFile:PhonePwdFilePath];
            
//            [MBProgressHUD showSuccess:@"登录成功" toView:self.view];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO userInfo:@{@"isLogin":@"true"}];
            });
            
        }else{
            [MBProgressHUD showSuccess:returnValue[@"exp"] toView:self.view];
        }
    } failure:^{
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        RequestFailure;
    }];
}

//点击登陆后的操作
- (void)loginWithUsername:(NSString *)username password:(NSString *)password
{
    //异步登陆账号
    __weak typeof(self) weakself = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        EMError *error = [[EMClient sharedClient] loginWithUsername:username password:password];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (!error) {
                //设置是否自动登录
                
                [[EMClient sharedClient].options setIsAutoLogin:YES];
                //获取数据库中数据
                [MBProgressHUD showHUDAddedTo:weakself.view animated:YES];
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    [[EMClient sharedClient] migrateDatabaseToLatestSDK];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [[ChatDemoHelper shareHelper] asyncGroupFromServer];
                        [[ChatDemoHelper shareHelper] asyncConversationFromDB];
                        [[ChatDemoHelper shareHelper] asyncPushOptions];
                        [MBProgressHUD hideAllHUDsForView:weakself.view animated:YES];
                        
                        //保存最近一次登录用户名
                        [weakself saveLastLoginUsername];
                    });
                });
            }
        });
    });
}

#pragma  mark - private
- (void)saveLastLoginUsername
{
    NSString *username = [[EMClient sharedClient] currentUsername];
    if (username && username.length > 0) {
        NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
        [ud setObject:username forKey:[NSString stringWithFormat:@"em_lastLogin_username"]];
        [ud synchronize];
    }
}

- (NSString*)lastLoginUsername
{
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    NSString *username = [ud objectForKey:[NSString stringWithFormat:@"em_lastLogin_username"]];
    if (username && username.length > 0) {
        return username;
    }
    return nil;
}

#pragma mark    -------remeberButtonClick   忘记密码-------
-(void) remeberButtonClick
{
    [self.navigationController pushViewController:[SYS_RemeberPwdVC new] animated:YES];
}


#pragma mark    --------UITextFieldDelegate---------
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;

{  //string就是此时输入的那个字符 textField就是此时正在输入的那个输入框 返回YES就是可以改变输入框的值 NO相反
    
    
    NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string]; //得到输入框的内容
    if (textField.tag == 8888)  //判断是否时我们想要限定的那个输入框
        
    {
        if ([toBeString length] > 20) { //如果输入框内容大于20则弹出警告
            
            textField.text = [toBeString substringToIndex:11];
            
            return NO;
            
        }
    }else if (textField.tag==9999){
        if ([toBeString length] > 20) { //如果输入框内容大于11则弹出警告
            
            textField.text = [toBeString substringToIndex:11];
            
            return NO;
            
        }
        
    }
    
    return YES;
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

- (void)backToPrevious
{
    [self.navigationController popViewControllerAnimated:YES];
}




@end
